package com.ruoyi.api.mqtt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.api.dailyWork.controller.MqMessageVo;
import com.ruoyi.api.wsmessage.domain.Wsmessage;
import com.ruoyi.api.wsmessage.service.IWsmessageService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.cache.user.UserCacheService;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.util.HttpClientUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class MqttService {
  @Value("${wspaas.wsCommandUrl}")
  private String cmdUrl;
  private static final Logger log = LoggerFactory.getLogger(MqttService.class);
  @Autowired
  private UserCacheService userCacheService;
  @Autowired
  private IWsmessageService wsmessageService;
  @Autowired
  private ISysUserService sysUserService;
  @Value("${sysCfg.adminRoleIds}")
  private List<Long> managerRoleIds;
  @Autowired
  private ThreadPoolTaskExecutor threadPoolTaskExecutor;

  public void publish(int qos, String topic, String msg) {
    String url = cmdUrl + "/api/cmd/msg/send";
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("qos", qos);
    jsonObject.put("topic", topic);
    log.error("topic==" + topic+"qos="+qos+",MSG="+msg);
    jsonObject.put("msg", msg);
    String s = HttpClientUtil.doPost(url.toString(), jsonObject);
    if(!StringUtils.isEmpty(s) && "-1".equalsIgnoreCase(s)){
      log.error("topic msg failed=="+topic);
    }else {
      log.error("topic msg success=="+topic);
    }
  }

  public void sendMessage(int scope,Wsmessage wsmessage)  {
    if (StringUtils.isEmpty(wsmessage.getEntityId())) return;
    List<SysUser> sysUsersManagers = sysUserService.selectUsersByRoleIds(managerRoleIds.toArray(new Long[1]));
    if(sysUsersManagers !=null && sysUsersManagers.size() >0){
      //平台
      for (SysUser userReceiver : sysUsersManagers) {
        coypWsmssage(wsmessage, userReceiver);
      }
    }
    if(scope == 1){//外部指定推送人
      msgPublishAndPersists(wsmessage);
    }else if(scope == 2){//暂时只推上级
      SysUser userReceiver = userCacheService.getParent(wsmessage.getUserSenderId());//userSender.getUserId()
      if (userReceiver != null) {
        coypWsmssage(wsmessage, userReceiver);
      }
    }
  }

  private void coypWsmssage(Wsmessage wsmessage, SysUser userReceiver) {
    try {
      Wsmessage tmp=new Wsmessage();
      BeanUtils.copyProperties(tmp,wsmessage);
      tmp.setUserReceiverId(userReceiver.getUserId().toString());
      tmp.setUserReceiverLoginName(userReceiver.getLoginName());
      msgPublishAndPersists(tmp);
    }catch (Exception e){
      e.getMessage();
    }
  }


  public void msgPublishAndPersists(Wsmessage wsmessage){
    threadPoolTaskExecutor.execute(new Runnable() {
      @Override
      public void run() {
        try {
          wsmessageService.insertWsmessage(wsmessage);

          String s = JSON.toJSONString(wsmessage);
          Base64 base64 = new Base64();
          String base64Sign = base64.encodeToString(s.getBytes("UTF-8"));
          System.out.println(s);
          publish(1, "u" + wsmessage.getUserReceiverId(), base64Sign);

        }catch (Exception e){
          e.printStackTrace();
          log.error("====msgPublishAndPersists=="+e.getMessage());
        }
      }
    });
  }
}
